using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using SubSonic.SqlGeneration.Schema;
using Webbness.Mvc.SubSonic;

namespace Webbness.Mvc.Models
{
    public abstract class SecurityRole<TRole, TJoin, TUser> : Record
        where TUser : SecurityUser<TUser, TJoin, TRole>, new()
        where TRole : SecurityRole<TRole, TJoin, TUser>, new()
        where TJoin : SecurityUserInRole<TRole, TJoin, TUser>, new()
    {
        private List<TUser> _users;

        [SubSonicPrimaryKey]
        [HiddenInput]
        [ScaffoldColumn(false)]
        [ScaffoldInList(false)]
        public override int Id { get; set; }

        [DisplayName("Role Name")]
        public virtual string RoleName { get; set; }

        [DisplayName("Description")]
        public virtual string Description { get; set; }


        protected List<TJoin> UsersInRole
        {
            get { return GetForeignList<TJoin>(m => m.RoleID == Id); }
        }

        [ScaffoldColumn(false)]
        [ScaffoldInList(false)]
        public virtual List<TUser> Users
        {
            get
            {
                if (_users == null)
                {
                    IQueryable<TUser> i = from r in Repository.Repo.All<TUser>() join uir in Repository.Repo.All<TJoin>() on r.Id equals uir.UserID where (Id == uir.RoleID) select r;
                    _users = i.ToList();
                }
                return _users;
            }
        }

        public override string ToString()
        {
            return RoleName;
        }
    }
}